import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { Button, message, Modal, Typography, Space, Tag,Image } from 'antd';
import CreateProduct from './component/CreateProduct';
import UpdateProduct from './component/UpdateProduct';
import { queryProduct,addProduct,updateProduct,removeProduct,queryProductTypeList,queryProductCategoryVOList,querySaleChannelList } from '@/services/ant-design-pro/apis';
const { Text, Link } = Typography;

const BizType = (props) => {
  const actionRef = useRef();
  const [selRows, setSelRows] = useState();
  const [createModalVisible, handleModalVisible] = useState(false);
  const [updateModalVisible, handleUpdteModalVisible] = useState(false);
  const [stepFormVals, setStepFormVals] = useState();
  const [productTypeList, setProductTypeList] = useState([]);
  const [productCategoryVOList, setProductCategoryVOList] = useState([]);
  const [saleChannelList, setSaleChannelList] = useState([]);

  useEffect(() => {
    queryProductTypeList().then((val) => {
      setProductTypeList(val);
    });
    queryProductCategoryVOList().then((val) => {
      setProductCategoryVOList(val);
    });
    querySaleChannelList().then((val) => {
      setSaleChannelList(val);
    });
  }, []);


  const handleDel = async (record) => {
    Modal.confirm({
      title: '删除产品',
      content: '确认删除产品？',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        const hide = message.loading('正在删除');
        try {
          await removeProduct({ id: record.id });
          hide();
          message.success('删除成功');
          actionRef.current.reload();
        } catch (error) {
          hide();
          message.error('删除失败请重试！');
          return false;
        }
      },
    });
  };

  const handleAdd = async (value) => {
    const hide = message.loading('正在添加');
    try {
      await addProduct({ ...value });
      hide();
      handleModalVisible(false);
      message.success('添加成功');
      actionRef.current.reload();
      return true;
    } catch (error) {
      hide();
      message.error('添加失败');
      return false;
    }
  };

  const handleUpdate = async (value) => {
    const hide = message.loading('正在配置');
    try {
      await updateProduct({ ...value });
      hide();
      handleUpdteModalVisible(false);
      setStepFormVals(undefined);
      message.success('配置成功');
      actionRef.current.reload();
    } catch (error) {
      hide();
      message.error('配置失败');
    }
  };

  function CZRender(record) {
    var item = [
      <a
        key="edit"
        onClick={() => {
          setStepFormVals(record);
          handleUpdteModalVisible(true);
        }}
      >
        配置
      </a>,
      <a
        key="delete"
        onClick={() => {
          handleDel(record);
        }}
      >
        删除
      </a>,
    ];
    return item;
  }

  const IMGRender = (record) => {
    var item = (
      <Image
        key={record.id}
        width={60}
        preview={{
          imageRender: () => <video muted width="100%" controls src={record.img} />,
          toolbarRender: () => null,
        }}
        src={record.img}
      />
    );
    return item;
  };

  const brandRender = (entity) => {
    if (entity.brandId <= 0) {
      return null;
    }
    var colorList = [
      'magenta',
      'red',
      'volcano',
      'orange',
      'gold',
      'lime',
      'green',
      'cyan',
      'blue',
      'geekblue',
      'purple',
    ];
    var item = [];
    const randomIndex = Math.floor(Math.random() * colorList.length);
    const randomValue = colorList[randomIndex];
    const index = productCategoryVOList.findIndex((item) => item.value == entity.brandId);
    item.push(
      <Tag key={entity.brandId} color={randomValue}>
        品牌:{productCategoryVOList[index]?.label}
      </Tag>,
    );
    if (entity.brandSkuId > 0) {

      const randomIndex = Math.floor(Math.random() * colorList.length);
      const randomValue = colorList[randomIndex];
      const indexSku = productCategoryVOList[index]?.children?.findIndex((item) => item.value == entity.brandSkuId);
      item.push(
        <Tag key={entity.brandSkuId} color={randomValue}>
          规格:{productCategoryVOList[index]?.children[indexSku]?.label}
        </Tag>,
      );
    }
    return item;
  };


  function tagRender(record) {
    var colorList = [
      'magenta',
      'red',
      'volcano',
      'orange',
      'gold',
      'lime',
      'green',
      'cyan',
      'blue',
      'geekblue',
      'purple',
    ];
    var item = [];
    record.channels.map((a) => {
      const randomIndex = Math.floor(Math.random() * colorList.length);
      const randomValue = colorList[randomIndex];
      const index = saleChannelList.findIndex((item) => item.value == a);
      item.push(
        <Tag key={a + '' + randomIndex} color={randomValue}>
          {saleChannelList[index].label}
        </Tag>,
      );
    });
    return item;
  }



  const columns = [
    {
      title: '产品名称',
      dataIndex: 'goodsName',
    },
    {
      title: '产品编码',
      dataIndex: 'goodsCode',
    },
    {
      title: '图片',
      dataIndex: 'img',
      hideInSearch: true,
      render: (demo, record) => [IMGRender(record)],
    },
    {
      title: '产品面值',
      dataIndex: 'faceValue',
      hideInSearch: true,
    },
    {
      title: '产品售价',
      dataIndex: 'price',
      hideInSearch: true,
    },
    {
      title: '产品库存',
      dataIndex: 'stockNum',
      hideInSearch: true,
    },
    {
      title: '终端限价',
      dataIndex: 'limitPrice',
      hideInSearch: true
    },
    {
      title: '品牌信息',
      valueType: 'cascader',
      dataIndex: 'productBrand',
      hideInSearch:true,
      render: (_, entity) => [brandRender(entity)],
    },
    {
      title: '渠道限制',
      dataIndex: 'channels',
      hideInSearch:true,
      render: (_, entity) => [tagRender(entity)],
    },
    {
      title: '产品类型',
      dataIndex: 'typeCode',
      valueEnum: {
        "Equity": {
          text: '自动充值'
        },
        "Card": {
          text: '卡密兑换',
        },
      },
      hideInSearch:true
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        "99": {
          text: '上架',
          status: 'Success',
        },
        "-99": {
          text: '下架',
          status: 'Error',
        },
      },
      formItemProps: {
        initialValue: undefined,
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [CZRender(record)],
    }
  ];

  return (
    <PageContainer>
      <ProTable
        columns={columns}
        actionRef={actionRef}
        headerTitle="产品列表"
        rowKey="id"
        request={queryProduct}
        rowSelection={{
          onChange: (_, selRows) => {
            setSelRows(selRows);
          },
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            新建
          </Button>,
        ]}
      ></ProTable>
            <CreateProduct
        createModalVisible={createModalVisible}
        handleModalVisible={() => {
          handleModalVisible(false);
        }}
        handCreate={() => {}}
        onSubmit={async (values) => {
          await handleAdd(values);
        }}
        productTypeList={productTypeList}
        saleChannelList={saleChannelList}
        productCategoryVOList={productCategoryVOList}
        onCancel={() => {
          handleModalVisible(false);
        }}
      >
      </CreateProduct>

      {stepFormVals && Object.keys(stepFormVals).length ? (
        <UpdateProduct
          updateModalVisible={updateModalVisible}
          handleModalVisible={() => {
            handleUpdteModalVisible(false);
            setStepFormVals(undefined);
          }}
          onSubmit={async (values) => {
            await handleUpdate({ ...values, id: stepFormVals.id });
          }}
          productTypeList={productTypeList}
          productCategoryVOList={productCategoryVOList}
          saleChannelList={saleChannelList}
          onCancel={() => {
            handleUpdteModalVisible(false);
            setStepFormVals(undefined);
          }}
          values={stepFormVals}
        >
        </UpdateProduct>
      ) : null}
    </PageContainer>
    
  );
};

export default BizType;
